package com.chinaunicom.emergency.util;

import com.chinaunicom.emergency.filter.ResponseWrapper;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;

/**
 * @author liliang
 * @date 2019-12-13
 * http服务类
 */
@Log4j2
public class HttpUtil {

    /**
     * 打印请求内容
     * @param request
     * @param body
     */
    public static void printRequest(HttpServletRequest request,String body) {
        InputStream in = null;
        try {
            Enumeration<String> enumeration = request.getHeaderNames();
            StringBuffer headers = new StringBuffer();
            while (enumeration.hasMoreElements()) {
                String name = enumeration.nextElement();
                String value = request.getHeader(name);
                headers.append(name + ":[" + value+"]").append(", ");
            }
            String uri = request.getRequestURL().toString();
            if("GET".equals(request.getMethod()) || "DELETE".equals(request.getMethod())){
                body = request.getQueryString();
            }
            String method = request.getMethod();
            String contentType = request.getContentType();
            String encoding = request.getCharacterEncoding();
            log.info("\nweb request -----------------------------------------------\n" +
                            "Address : {}\n" +
                            "Http-Method : {}\n" +
                            "Encoding : {}\n" +
                            "Content-Type : {}\n" +
                            "Client-Ip : {}\n" +
                            "Headers : {}\n" +
                            "Params : {}\n" +
                            "------------------------------------------------------------",
                    uri,
                    method,
                    encoding,
                    contentType,
                    getRealIP(request),
                    headers,
                    body);
        } catch (Exception e) {
            log.error("打印web请求异常",e);
        }

    }

    /**
     * 打印响应内容
     * @param responseWrapper
     * @param url
     */
    public static void printResponse(HttpServletRequest request, ResponseWrapper responseWrapper, String url) {
        String responseBody = "大内容隐藏";
        if (responseWrapper.getMyOutputStream() == null){
            if (responseWrapper.getMyWriter() != null){
                if(url.indexOf("show/file") == -1 && url.indexOf("download/file") == -1 && url.indexOf("/content") == -1){
                    responseBody = responseWrapper.getMyWriter().getContent();
                }
                //一定要flush，responseBody会被复用
                responseWrapper.getMyWriter().myFlush();
            }
        }else {
            if(url.indexOf("show/file") == -1 && url.indexOf("download/file") == -1 && url.indexOf("/content") == -1){
                responseBody = responseWrapper.getMyOutputStream().getBuffer();
            }
            //一定要flush，responseBody会被复用
            responseWrapper.getMyOutputStream().myFlush();
        }

        Collection<String> enumeration = responseWrapper.getHeaderNames();
        StringBuffer headers = new StringBuffer();
        Iterator it = enumeration.iterator();
        while (it.hasNext()) {
            String name = (String)it.next();
            String value = responseWrapper.getHeader(name);
            headers.append(name + ":[" + value + "]").append(", ");
        }
        int status = responseWrapper.getStatus();
        log.info("\nweb response -----------------------------------------------\n" +
                        "Address : {}\n" +
                        "Http-Method : {}\n" +
                        "Http Code : {}\n" +
                        "Response Header : {}\n" +
                        "Response Element : {}\n" +
                        "------------------------------------------------------------",
                url,
                request.getMethod(),
                status,
                headers,
                responseBody);
    }

    /**
     * 获取请求的真实IP
     * @param request
     * @return
     */
    public static String getRealIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }

    public static void returnJson(HttpServletResponse response, String json) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            log.error("response error",e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

}
